package cn.com.roy.thread.t4_1_13.trylockparam;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class Myservice {
    public ReentrantLock lock = new ReentrantLock();

    public void testMethod(){
        try {
            if(lock.tryLock(3, TimeUnit.SECONDS)){ //在指定的时间内锁定未被其他线程保持，且未被阻断则获得锁
                System.out.println(Thread.currentThread().getName() + "获得锁，时间："+System.currentTimeMillis() );
                Thread.sleep(5000);
            }else{
                System.out.println(Thread.currentThread().getName() + "没有获得锁");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }
}
